package com.me.study.concurrent.thread;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AtomicInteger 测试：
 *
 * @author ME
 * @date 2019/1/31 18:16
 */
public class TestAtomic implements Runnable {
    AtomicInteger atomicInteger = new AtomicInteger(0);
    int count = 0;
    CopyOnWriteArrayList list = new CopyOnWriteArrayList();

    @Override
    public void run() {
        while (true) {
            // int i1 = count++;
            int i1 = atomicInteger.getAndIncrement();// 安全的 count++
            if (i1 >= 10000) {
                // System.out.println("i1: " + i1);
                break;
            }
            list.add(i1);
        }
        // System.out.println(Thread.currentThread().getDisplayName() + " count: " + list.size());
        System.out.println(Thread.currentThread().getName() + " count: " + atomicInteger.get());
    }

    public static void main(String[] args) {
        TestAtomic testThread1 = new TestAtomic();
        Thread t1 = new Thread(testThread1);
        Thread t2 = new Thread(testThread1);
        Thread t3 = new Thread(testThread1);
        // t1.setDisplayName("Thread-1: ");
        // t2.setDisplayName("Thread-2: ");
        // t3.setDisplayName("Thread-3: ");
        t1.start();
        t2.start();
        t3.start();

        System.out.println(new AtomicInteger().getAndIncrement());
        System.out.println(new AtomicInteger().incrementAndGet());
    }
}
